package handlers

import (
	"github.com/labstack/echo/v4"
	// "fmt"

	"night-school-api/models"
	"night-school-api/utils"
	"night-school-api/database"
)

func Comment(c echo.Context) error {
	uid := c.Get("uid").(int)

	var req models.Comment

	// 解析 JSON 请求
	if err := c.Bind(&req); err != nil {
		return utils.JSONError(c, "参数错误: " + err.Error())
	}

	if err := c.Validate(&req); err != nil {
		return err
	}

	req.UserID = uid

	db := database.DB

	var course models.Course
	db.First(&course, req.CourseID)
	if course.ID <= 0 {
		return utils.JSONError(c, "课程不存在")
	}

	var enrollment models.Enrollment
	db.First(&enrollment, "course_id = ? AND user_id = ?", course.ID, uid)
	if enrollment.ID <= 0 {
		return utils.JSONError(c, "您不能评论自己未参加的课程")
	}

	err := db.Model(&models.Comment{}).Create(&req).Error
	if err != nil {
		c.Logger().Info("评论课程失败: " + err.Error())
		return utils.JSONError(c, "评论课程失败")
	} else {
		return utils.JSONSuccess(c, nil, "评论课程成功")
	}
}
